package com.wsc.frontier;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import com.wsc.frontier.database.DataBaseDetails;
import com.wsc.frontier.database.MasterDB;

/**
 *
 * @author N V Reddy
 */
public class Frontier {
	
    public static boolean shutdown = false;
    private boolean is_frontier_up = false;
    private String Frontierlogfile,FrontierMaintenancelogfile;
    private FrontierConfig fconfig;
    private FrontierServer fserver;
    private FrontierClient fclient = new FrontierClient();
    private MasterDB mdb;
    
    private Logger log=Logger.getLogger(Frontier.class.getName());
    
    //starting frontier
    
    public void startFrontier() throws Exception{
    
    	//logfile creation
        
        //creation of Frontier Details 
        FrontierDetails.loadXmlFile();
        FrontierDetails.getAllDetails();
        
       log.info("All details of Frontier fetched successfully.");
        
        //creation of Database Details
        
        DataBaseDetails.loadXmlFile();
		DataBaseDetails.getAllDetails();
		log.info("All details of database fetched successfully.\n");
        
        //creation of Frontier configuration object
        fconfig = new FrontierConfig();
        log.info("FrontierConfiguration object created successfully");
        fconfig.getDetails();
        /*common directory checking
        if(!fconfig.commonDirectory()){
            Logger.writeLog(Frontierlogfile, "Common directory structure is not present");
            Logger.writeLog(Frontierlogfile, "Creating Common directory structure.");
            fconfig.createCommonDirectory();
            Logger.writeLog(Frontierlogfile, "Common directory structure created Successfully.");
        }
        else{
            Logger.writeLog(Frontierlogfile, "Common directory structure avalible.");
        }*/
        
        //starting mysql server
        if(!fconfig.mysqlStartup()){
        	log.info("mysql server is not avalible/starting....check FrontierConfig logfile for further details.\n");
            System.exit(1);
        }
        else{
        	log.info("Mysql server started successfully");
        }
        
        //checking database
        if(!fconfig.mysqlDatabase()){
        	log.info("required database structure is not avalible..");
            System.exit(2);
        }
        else{
        	log.info("required data found in mysql server. \n");
            
        }
        
        //cleaning previous data
        log.info("Cleaning previous data started.\n");
    //    fconfig.cleanPreviousData();
        log.info("Previous data cleaned successfully.\n");
        
        log.info("Frontier configuration done.");
        
        //starting the Frontier server
        fserver = new FrontierServer();
        
        Thread t = new Thread(fserver);
        t.start();
        
        mdb = new MasterDB();
        int attempt = 1;
        while(true){
        	fclient.sendRequest(FrontierDetails.getServerIP(),FrontierDetails.getFrontierServerPort(),"heartbeat");
        	int code = fclient.statuscode;
        	if(code == 200){
        		log.info("Frontier Server respond properly...");
        		is_frontier_up = true;
        		if(mdb.getConnection(DataBaseDetails.getDbUrl(),DataBaseDetails.getDatabaseDriver() ,DataBaseDetails.getDatabaseUser(),DataBaseDetails.getDatabasePassword())){
        			String data[] = new String[5];
            		data[0] = "frontier";
            		data[1] = FrontierDetails.getServerIP();
            		data[2] = "on";
            		Date dt = new Date();
                    DateFormat df = new SimpleDateFormat("yyyy-mm-dd-hh-mm-ss");
            		data[3] = df.format(dt);
            		data[4] = "----";
            		if(mdb.update(DataBaseDetails.getMasterTable(), data,"starttime")){
            			log.info("Frontier startup details updated successfully...");
            		}
            		else{
            			log.info("Unable to update Frontier start up details...");
            		}
        		}
        		else{
        			log.info("Unable to update Frontier start up details...");
        		}
        		
        		break;
        	}
        	else{
        		log.info("Frontier Server not responding attempt..."+attempt);
        		if(attempt == 6){
        			log.info("Frontier Server respond properly...check log file for futher details...\n");
        			log.info("Shutting down the frontier...\n");
        			System.exit(4);
        		}
        		Thread.sleep(2000);
        		attempt++;
        	}
        }
        
        
    }
    
    public void frontierMaintenance() throws Exception{
        while(!shutdown){
            //checking mysql connection
        	log.info("checking mysql connection");
            int attempt = 1;
            while(!shutdown){
            	if(fconfig.mysqlCheckup()){
            		log.info("mysql connection is ok");
                    Thread.sleep(5000);
                    break;
            	}
            	else{
            		if(attempt == 6){
            			log.info("mysql is down...... shutting down frontier node...\n");
            			shutdown = true;
            			break;
            		}
            		log.info("look like mysql is down. trying to up again.....attempt number "+attempt);
            		attempt++;
            		fconfig.mysqlStartup();
            	}
            }
        }
        
        if(shutdown){
        	fserver.stopServer();
        	log.info("Frontier Server stopped successfully......\n");
        	String data[] = new String[5];
    		data[0] = "frontier";
    		data[1] = FrontierDetails.getServerIP();
    		data[2] = "off";
    		Date dt = new Date();
            DateFormat df = new SimpleDateFormat("yyyy-mm-dd-hh-mm-ss");
    		data[3] = "----";
    		data[4] = df.format(dt);
    		if(mdb.update(DataBaseDetails.getMasterTable(), data,"stoptime")){
    			log.info("Frontier shutdown details updated successfully...");
    		}
    		else{
    			log.info("Unable to update Frontier shutdown details...");
    		}
        }
        
        log.info("Frontier is shutdown....\n");
    }

    //main methode
    public static void main(String s[]) throws Exception{
    	
        //Creation of frontier object
        Frontier fron = new Frontier();
        
        //Starting Frontier
        fron.startFrontier();
        
        //Frontier Maintenance
        fron.frontierMaintenance();
        
        
    }
}
